#include "rardelegate.h"


RarDelegate::RarDelegate( QObject * parent )
    : QItemDelegate(parent)
{
star.load(":/binary/star.png");
}

QWidget * RarDelegate::createEditor( QWidget * parent,
                                     const QStyleOptionViewItem &,
                                     const QModelIndex & ) const
{
QSpinBox * editor = new QSpinBox(parent);
editor->setMinimum(0);
editor->setMaximum(5);
editor->setPrefix( QLatin1String("R") );
editor->setSingleStep(1);
editor->setButtonSymbols( QAbstractSpinBox::PlusMinus );
editor->setAccelerated(false);
editor->installEventFilter( const_cast<RarDelegate *>(this) );
return editor;
}

void RarDelegate::setEditorData( QWidget * editor,
                                 const QModelIndex & index ) const
{
int value = index.model()->data( index, Qt::DisplayRole ).toInt();
QSpinBox * spinBox = static_cast<QSpinBox *>(editor);
spinBox->setValue(value);
}

void RarDelegate::setModelData( QWidget * editor,
                                QAbstractItemModel * model,
                                const QModelIndex & index ) const
{
QSpinBox * spinBox = static_cast<QSpinBox *>(editor);
double value = spinBox->value();
model->setData( index, value );
}

void RarDelegate::updateEditorGeometry( QWidget * editor,
                                        const QStyleOptionViewItem & option,
                                        const QModelIndex & ) const
{
editor->setGeometry(option.rect);
}

void RarDelegate::paint( QPainter * painter,
                         const QStyleOptionViewItem & option,
                         const QModelIndex &index) const
{
    if (index.column() == 4)
    {
    const QAbstractItemModel * model = index.model();
    QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
                              ?
                              QPalette::Inactive
                              :
                              QPalette::Disabled;

        if (option.state & QStyle::State_Selected)
        {
        painter->fillRect( option.rect,
                           option.palette.color(cg, QPalette::Highlight) );
        }

    int rating = model->data( index, Qt::DisplayRole ).toInt();
    int width = star.width();
    int height = star.height();
    int x = option.rect.x();
    int y = option.rect.y() + ( option.rect.height() / 2 ) - ( height / 2 );
        for ( int i = 0; i < rating; ++i )
        {
        painter->drawPixmap( x, y, star );
        x += width;
        }
    }
}

